/*
 * $Author: kidbaw $
 * $Revision: 59 $
 * $Date: 2012-03-23 22:44:48 +0700 (Fri, 23 Mar 2012) $
 *
 */

#import "SupportFunction.h"
#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMediaItem.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MPMoviePlayerController.h>
#import "Define.h"
#import "AppViewController.h"
//#import "KardsDataManager.h"
//#import "UserDataManager.h"
//#import "FontLabel.h"
//#import "FontLabelStringDrawing.h"
//#import "FontManager.h"
//#import "Utilities.h"

#define MILE_STANDARD 5280.0
#define KM_STANDARD 0.0003048

#pragma mark - Debug log
void VKLoga(NSString *format,...)
{
#if VKDEBUG
    {
        va_list args;
        va_start(args,format);
        NSLogv(format, args);
        va_end(args);
    }
#endif
}

#pragma mark - UIDevice

@implementation UIDevice (Resolutions)

- (UIDeviceResolution)resolution
{
    UIDeviceResolution resolution = UIDeviceResolution_Unknown;
    UIScreen *mainScreen = [UIScreen mainScreen];
    CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
    CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if (scale == 2.0f) {
            if (pixelHeight == 960.0f)
                resolution = UIDeviceResolution_iPhoneRetina35;
            else if (pixelHeight == 1136.0f)
                resolution = UIDeviceResolution_iPhoneRetina4;
            
        } else if (scale == 1.0f && pixelHeight == 480.0f)
            resolution = UIDeviceResolution_iPhoneStandard;
        
    } else {
        if (scale == 2.0f && pixelHeight == 2048.0f) {
            resolution = UIDeviceResolution_iPadRetina;
            
        } else if (scale == 1.0f && pixelHeight == 1024.0f) {
            resolution = UIDeviceResolution_iPadStandard;
        }
    }
    
    return resolution;
}

@end

#pragma mark - SupportFunction

@implementation SupportFunction

typedef enum {
	libUserInterfaceIdiomUnknown = -1,
    libUserInterfaceIdiomPhone,
    libUserInterfaceIdiomPad,
} libUserInterfaceIdiom;

static libUserInterfaceIdiom g_interfaceIdiom = libUserInterfaceIdiomUnknown;
+ (BOOL)deviceIsIPad
{
#ifdef IS_SUPPORTED_IPAD
	if ( g_interfaceIdiom == libUserInterfaceIdiomUnknown ) {
		switch ( UI_USER_INTERFACE_IDIOM() ) {
			case UIUserInterfaceIdiomPhone:
				g_interfaceIdiom = libUserInterfaceIdiomPhone;
				break;
				
			case UIUserInterfaceIdiomPad:
				g_interfaceIdiom = libUserInterfaceIdiomPad;
				break;
		}
	}
	return (g_interfaceIdiom == libUserInterfaceIdiomPad);
#else
    g_interfaceIdiom = libUserInterfaceIdiomUnknown;
    return NO;
#endif
    g_interfaceIdiom = libUserInterfaceIdiomUnknown;
}


+(NSData*)ResizePhoto:(UIImage*)img {
    CGSize origSize = img.size;
    NSInteger newHeight = origSize.height;
    NSInteger newWidth = origSize.width;
    NSInteger maxHeight = 720;
    NSInteger maxWidth = 720;
    
    //Image is taller than it is wide or square
    if(origSize.height > origSize.width && origSize.height > maxHeight) {
        float scale = origSize.height/maxHeight;
        newHeight = maxHeight;
        newWidth = origSize.width/scale;
        
    }
    //Image is wider than it is tall
    else if(origSize.width > origSize.height && origSize.width > maxWidth) {
        float scale = origSize.width/maxWidth;
        newWidth = maxWidth;
        newHeight = origSize.height/scale;
        
    }
    //Else image is too small to need resizing
    
    CGSize newSize = CGSizeMake(newWidth, newHeight);
    NSUInteger imgSize = 0;
    float imgQuality = .95;
    NSData* resizedImageData = nil;
    do {
        UIGraphicsBeginImageContext(newSize);
        [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        resizedImageData = UIImageJPEGRepresentation(newImage, imgQuality);
        imgSize = [resizedImageData length];
        imgQuality -= .1;
        
        //VKLog(@"resizedImageData size = %d", imgSize);
    } while (imgSize > 512000 && imgQuality > 0);
    
    return resizedImageData;
}


+ (int)getDeviceHeight
{
#ifdef IS_SUPPORTED_LANDSCAPE
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) {
        if (IS_IPAD) {
            return _WIDTH_IPAD;
        }
        else if ([[UIDevice currentDevice] resolution] == UIDeviceResolution_iPhoneRetina4) {
            return _WIDTH_IPHONE_5;
        }
        else {
            return _WIDTH_IPHONE;
        }
    }
    else {
        if (IS_IPAD) {
            return _HEIGHT_IPAD;
        }
        else if ([[UIDevice currentDevice] resolution] == UIDeviceResolution_iPhoneRetina4) {
            return _HEIGHT_IPHONE_5;
        }
        else {
            return _HEIGHT_IPHONE;
        }
    }
#else
    if (IS_IPAD) {
        return _HEIGHT_IPAD;
    }
    else if ([[UIDevice currentDevice] resolution] == UIDeviceResolution_iPhoneRetina4) {
        return _HEIGHT_IPHONE_5;
    }
    else {
        return _HEIGHT_IPHONE;
    }
#endif
}

+ (int)getDeviceWidth
{
#ifdef IS_SUPPORTED_LANDSCAPE
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) {
        if (IS_IPAD) {
            return _HEIGHT_IPAD;
        }
        else if ([[UIDevice currentDevice] resolution] == UIDeviceResolution_iPhoneRetina4) {
            return _HEIGHT_IPHONE_5;
        }
        else {
            return _HEIGHT_IPHONE;
        }
    }
    else {
        if (IS_IPAD) {
            return _WIDTH_IPAD;
        }
        else if ([[UIDevice currentDevice] resolution] == UIDeviceResolution_iPhoneRetina4) {
            return _WIDTH_IPHONE_5;
        }
        else {
            return _WIDTH_IPHONE;
        }
    }
#else
    if (IS_IPAD) {
        return _WIDTH_IPAD;
    }
    else if ([[UIDevice currentDevice] resolution] == UIDeviceResolution_iPhoneRetina4) {
        return _WIDTH_IPHONE_5;
    }
    else {
        return _WIDTH_IPHONE;
    }
#endif
}

+ (int)getKeyboardHeight
{
#ifdef IS_SUPPORTED_LANDSCAPE
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) {
        if (IS_IPAD) {
            return HEIGHT_IPAD_KEYBOARD_LANDSCAPE;
        }
        else
            return HEIGHT_IPHONE_KEYBOARD_LANDSCAPE;
    }
    else {
        if (IS_IPAD) {
            return HEIGHT_IPAD_KEYBOARD;
        }
        else
            return HEIGHT_IPHONE_KEYBOARD;
    }
#else
    if (IS_IPAD) {
        return HEIGHT_IPAD_KEYBOARD;
    }
    else
        return HEIGHT_IPHONE_KEYBOARD;
#endif
}

+ (float)convertFeetToMiles:(float)feet {
    return feet/MILE_STANDARD;
}

+ (NSString*)convertFeetDistanceToString:(float)feet {
    if (feet == -1) {
        return @"offline";
    }
    if ([SupportFunction isLocaleze]) {
        return [NSString stringWithFormat:@"%.1f %@",feet/MILE_STANDARD, [SupportFunction getDistanceUnitString]];
    } else {
        return [NSString stringWithFormat:@"%.1f %@",feet*KM_STANDARD, [SupportFunction getDistanceUnitString]];
    }
    
}

+ (NSString*)getDistanceUnitString {
    // return mile
    if ([SupportFunction isLocaleze]) {
        return @"mi";
    } else {
        // return km
        return @"km";
    }
}


+ (int)getKeyboardWidth
{
    return [self getDeviceWidth];
}

+ (NSMutableArray *)sortArray:(NSMutableArray *)source withKey:(NSString *)key
{
    if ([source count] < 1) {
        return nil;
    }
    if ([source count] == 1) {
        return source;
    }
    NSMutableArray *ma_Copy = [NSMutableArray arrayWithArray:source];
    NSSortDescriptor *sd_Temp = [[NSSortDescriptor alloc] initWithKey:key ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *a_Descriptor = [NSArray arrayWithObjects:sd_Temp, nil];
    NSMutableArray *ma_Sort = [NSMutableArray new];
    [ma_Sort addObjectsFromArray:[ma_Copy sortedArrayUsingDescriptors:a_Descriptor]];
    return ma_Sort;
}

+ (NSMutableArray *)sortArrayNumberic:(NSMutableArray *)source withKey:(NSString *)key
{
    if ([source count] < 1) {
        return nil;
    }
    if ([source count] == 1) {
        return source;
    }
    
    NSMutableArray *ma_Copy = [NSMutableArray arrayWithArray:source];
    NSSortDescriptor *sd_Temp  = [[NSSortDescriptor alloc] initWithKey:key ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
        return [((NSString *)obj1) compare:(NSString *)obj2 options:NSCaseInsensitiveSearch | NSNumericSearch];
    }];
    
    NSArray *a_Descriptor = [NSArray arrayWithObjects:sd_Temp, nil];
    NSMutableArray *ma_Sort = [NSMutableArray new];
    [ma_Sort addObjectsFromArray:[ma_Copy sortedArrayUsingDescriptors:a_Descriptor]];
    return ma_Sort;
    
//    NSArray *ma_Sort = [source sortedArrayUsingComparator:^(id firstObject, id secondObject) {
//        return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
//    }];
//
//    return [[NSMutableArray alloc] initWithArray:ma_Sort];
}

+ (NSString *)getStringDistanceFromLocation:(CLLocation *)fromLoc toLocation:(CLLocation *)toLoc {
    CLLocationDistance kilometers = [fromLoc distanceFromLocation:toLoc] / 1000; 
//    CLLocationDistance meters = [fromLoc distanceFromLocation:toLoc];
    
    return [NSString stringWithFormat:@"%.2fKm", kilometers];
}

+ (NSString *)getStringDistanceFromMeter:(double)meters {
//    int feet = meters; // Server: return to inches
//    int realMeter = inches / 0.0254;
    float realMeters = meters * 0.3048;
    
//    int feet = realMeters / 0.3048;
//    int yards = realMeters / 0.9144;
//    int miles = realMeters / 1609;
//    if (miles >= DOUBLE_DISTANCE_UNIT_MIN && miles <= DOUBLE_DISTANCE_UNIT_MAX*DOUBLE_DISTANCE_UNIT_MAX) {
//        return [NSString stringWithFormat:@"%i mi", miles];
//    }
//    else if (yards >= DOUBLE_DISTANCE_UNIT_MIN && miles <= DOUBLE_DISTANCE_UNIT_MIN) {
//        return [NSString stringWithFormat:@"%i yd", yards];
//    }
//    else if (feet >= 0 && yards <= DOUBLE_DISTANCE_UNIT_MIN) {
//        return [NSString stringWithFormat:@"%i ft", feet];
//    }
//    else
//        return [NSString stringWithFormat:@"∞"];
    
    float miles = realMeters / 1609;
    if (miles == 0) {
        return @"";
    }
    else if (miles <= DOUBLE_DISTANCE_UNIT_MAX*DOUBLE_DISTANCE_UNIT_MAX) {
        return [NSString stringWithFormat:@"%.1f mi", miles + 0.1];
    }
    else
        return [NSString stringWithFormat:@"∞"];
}

+ (NSMutableArray *)repairingJSONData:(NSArray *)jsonData
{
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:[jsonData count]];
    for (NSDictionary *dictionary in jsonData) {
        [result addObject:[dictionary mutableCopy]];
    }
    return result;
}

+ (CGRect)getFrameNotificationWithFont:(UIFont *)font andNotificationNumber:(int)num andAppearPosition:(enumVKNotificationAppearPosition)position andParentFrame:(CGRect)frame {
    CGRect newRect = CGRectZero;
    
    NSString *strNum = [NSString stringWithFormat:@"%i", num];
    CGSize sizeNotification = [strNum sizeWithFont:font];
    float widthNotification = sizeNotification.width + 12;
    float heightNotification = sizeNotification.height + 6;
    
    if (position == enumVKNotificationAppearPosition_Top_Left) {
        newRect = CGRectMake(-widthNotification/3, -heightNotification/3, widthNotification, heightNotification);
    }
    else if (position == enumVKNotificationAppearPosition_Top_Right) {
        newRect = CGRectMake(frame.size.width - widthNotification*2/3, -heightNotification/3, widthNotification, heightNotification);
    }
    else if (position == enumVKNotificationAppearPosition_Top_Right_Not_Margin_Right) {
        newRect = CGRectMake(frame.size.width - widthNotification, -heightNotification/3, widthNotification, heightNotification);
    }
    
    return newRect;
}

+ (NSString *)getObjectTextWithCount:(NSInteger)count withText:(NSString *)text withHidden:(BOOL)isHidden
{
    if (count == 0 && isHidden) {
        return [NSString stringWithFormat:@"%i %@",count, text];//@"";
    } else if (count <= 1)
        return [NSString stringWithFormat:@"%i %@",count, text];
    else if (count > 1)
        return [NSString stringWithFormat:@"%i %@s",count,text];
    return @"";
}

+ (CGRect)getRealImageFrameWithNewImage:(UIImage *)newImage andOriginalFrame:(CGRect)originalFrame {
    CGRect drawRect;
    CGFloat scaleSize;
    CGFloat scaleFactor;
    CGFloat widthFactor = newImage.size.width/originalFrame.size.width;
    CGFloat heightFactor = newImage.size.height/originalFrame.size.height;
    CGFloat scaledWidth;
    CGFloat scaledHeight;
    
    if (widthFactor < heightFactor) {
        scaleFactor = widthFactor;
        scaleSize = originalFrame.size.width/newImage.size.width;
    }
    else {
        scaleFactor = heightFactor;
        scaleSize = originalFrame.size.height/newImage.size.height;
    }
    
    scaledWidth  = originalFrame.size.width*scaleFactor;
    scaledHeight = originalFrame.size.height*scaleFactor;
    
    drawRect = CGRectMake(-(newImage.size.width - scaledWidth)/2, -(newImage.size.height - scaledHeight)/2, newImage.size.width, newImage.size.height);
    
    scaleSize = originalFrame.size.width/newImage.size.width;
    drawRect = CGRectMake(drawRect.origin.x*scaleSize, drawRect.origin.y*scaleSize, drawRect.size.width*scaleSize, drawRect.size.height*scaleSize);
    
    return drawRect;
}

+ (NSString *)getCurrentExternRevision {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}

+ (UIInterfaceOrientation)orientationWithURL:(NSURL *)url
{
    if (!url) {
        return UIInterfaceOrientationPortrait;
    }
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    
    AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
    CGSize size = [videoTrack naturalSize];
    CGAffineTransform txf = [videoTrack preferredTransform];
    
    if (size.width == txf.tx && size.height == txf.ty)
        return UIInterfaceOrientationLandscapeRight;
    else if (txf.tx == 0 && txf.ty == 0)
        return UIInterfaceOrientationLandscapeLeft;
    else if (txf.tx == 0 && txf.ty == size.width)
        return UIInterfaceOrientationPortraitUpsideDown;
    else
        return UIInterfaceOrientationPortrait;
}

+ (NSTimeInterval)sizeWithURL:(NSURL *)url
{
    if (!url) {
        return 0;
    }
    
    //AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url
                                            options:[NSDictionary dictionaryWithObjectsAndKeys:
                                            [NSNumber numberWithBool:YES],
                                            AVURLAssetPreferPreciseDurationAndTimingKey,
                                            nil]];
    
    NSTimeInterval durationInSeconds = 0.0;
    if (asset) 
        durationInSeconds = CMTimeGetSeconds(asset.duration) ;
    
    return durationInSeconds;
}

#pragma mark - Response Alert

+ (void)alertWithError:(int)error andMessage:(NSString *)message
{
    UIAlertView *_alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"ERROR: %i", error] message:message delegate:self cancelButtonTitle:STRING_ALERT_OK otherButtonTitles:nil];
    [_alert show];
}

void ALERT(NSString* title, NSString* message) { 
	UIAlertView *_alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:STRING_ALERT_OK otherButtonTitles:nil];
    [_alert show];
}

UIAlertView* UI_ALERT_VIEW(NSString* title, NSString* msg, id delegate, NSString* other_button, NSString* cancel_button)
{
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:title
                          message:msg
                          delegate:delegate
                          cancelButtonTitle:cancel_button
                          otherButtonTitles:other_button,nil];
    return alert;
}

 void alertView(NSString *title, NSString *message,NSString *dismissString){
    UIAlertView *_alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:dismissString otherButtonTitles:nil];
    [_alert show]; 
 }

+ (CGSize)getSizeForText:(NSString *)string  withFont:(UIFont *)font withMaxSize:(CGSize)maxSize
{
    //then calculate the size. systemFontOfSize depends on your font size
    //yourLabelWidth must be known and usually depends on scree size or if the tableview has an index
    CGSize textSize = [string sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
    return textSize;
}

#pragma mark - Date Formatter

+ (NSDate *)dateFromRFC1123String:(NSString *)string
{
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
	// Does the string include a week day?
	NSString *day = @"";
	if ([string rangeOfString:@","].location != NSNotFound) {
		day = @"EEE, ";
	}
	// Does the string include seconds?
	NSString *seconds = @"";
	if ([[string componentsSeparatedByString:@":"] count] == 3) {
		seconds = @":ss";
	}
	[formatter setDateFormat:[NSString stringWithFormat:@"%@dd MMM yyyy HH:mm%@ z",day,seconds]];
	return [formatter dateFromString:string];
}

+ (NSString *)stringFromDate:(NSDate *)date
{
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
	
    [formatter setDateFormat:[NSString stringWithFormat:@"EEE, dd MMM yyyy HH:mm:ss"]];
	return [formatter stringFromDate:date];
}

+ (NSString *)stringFromDateUseForName:(NSDate *)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
	
    [formatter setDateFormat:[NSString stringWithFormat:@"ddMMyyyyHHmmss"]];
	return [formatter stringFromDate:date];

}

+ (NSMutableDictionary *)repairingDictionaryWith:(NSDictionary *)dictionary 
{
    NSMutableDictionary *muDictionary = [[NSMutableDictionary alloc] init];
    NSArray *allKeys = [dictionary allKeys];
    for (int i = 0; i < [allKeys count]; i ++) {
        NSMutableDictionary *childDictionary = [dictionary objectForKey:[allKeys objectAtIndex:i]];
        NSString *key = [allKeys objectAtIndex:i];
        if ([childDictionary isKindOfClass:[NSDictionary class]]) {
            [muDictionary setValue:[self repairingDictionaryWith:[dictionary objectForKey:[allKeys objectAtIndex:i]]] forKey:key];
        } else {
            if ((NSNull *)[dictionary objectForKey:[allKeys objectAtIndex:i]] == [NSNull null]) {
                [muDictionary setObject:@"" forKey:[allKeys objectAtIndex:i]];
            }
            else {
                [muDictionary setObject:[dictionary objectForKey:[allKeys objectAtIndex:i]] forKey:[allKeys objectAtIndex:i]];
            }
        }
    }
    return muDictionary;
}

+(NSMutableDictionary *)normalizeDictionary:(NSMutableDictionary*)dictionary
{
    NSArray *allKeys = [dictionary allKeys];
    for (id key in allKeys) {
        id object = [dictionary objectForKey:key];
        if ([object isKindOfClass:[NSDictionary class]]) {
            [self normalizeDictionary:object];
        }
        else if ((NSNull *)[dictionary objectForKey:key] == [NSNull null]) {
            [dictionary setObject:@"" forKey:key];
        }
    }
    return dictionary;
}

+ (void)scalePickerView:(UIPickerView *)picker toSize:(CGSize)size {
    picker.frame = FRAME(0, 0, picker.frame.size.height * size.width / size.height, picker.frame.size.height);
    float widthScale = size.width / picker.bounds.size.width;
    float heightScale = size.height / picker.bounds.size.height;
    
    CGAffineTransform s0 = CGAffineTransformMakeScale (widthScale, heightScale);
    CGAffineTransform t0 = CGAffineTransformMakeTranslation (picker.bounds.size.width/2, picker.bounds.size.height/2);
    CGAffineTransform t1 = CGAffineTransformMakeTranslation (-picker.bounds.size.width/2, -picker.bounds.size.height/2);
    picker.transform = CGAffineTransformConcat (t0, CGAffineTransformConcat(s0, t1));
}

+ (NSString *)timeStringForDateCreated:(NSString *)created
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
    NSString* localAbbreviation = [localTimeZone abbreviation];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:localAbbreviation]];
    NSDate *date = [formatter dateFromString:created];
    [formatter setDateFormat:@"hh:mm a"];
    return [formatter stringFromDate:date];
}

+(NSDate*)dateForDateCreated:(NSString*)created
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
    NSString* localAbbreviation = [localTimeZone abbreviation];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:localAbbreviation]];
    NSDate *date = [formatter dateFromString:created];
    return date;
}

+ (NSString *)stringWithHiddenDateString:(NSString *)hiddenString {
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init] ;
    NSMutableArray *arrayComponents = (NSMutableArray *)[hiddenString componentsSeparatedByString:@"."];
    NSString *newString;
    if (arrayComponents.count > 1) {
        NSMutableArray *arrayComponents_01 = (NSMutableArray *)[[arrayComponents objectAtIndex:1] componentsSeparatedByString:@"-"];
        NSMutableArray *arrayComponents_02 = (NSMutableArray *)[[arrayComponents objectAtIndex:1] componentsSeparatedByString:@"+"];
        if (arrayComponents_02.count == 1 && arrayComponents_01.count == 1) {
            newString = [NSString stringWithFormat:@"%@+%@", [arrayComponents objectAtIndex:0], [arrayComponents objectAtIndex:1]];
        }
        else {
            newString = hiddenString;
        }
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZ"];
    }
    else {
        newString = hiddenString;
        [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    }
    
    NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
    NSString* localAbbreviation = [localTimeZone abbreviation];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:localAbbreviation]];
    NSDate *date = [formatter dateFromString:newString];
    [formatter setDateFormat:@"MM/dd/yyyy"];
//    VKLog(@"stringWithHiddenDateString: %@", [formatter stringFromDate:date]);
    return [formatter stringFromDate:date];
}

+ (NSString *)stringDateWeekFromDate:(NSString *)created
{
	NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
    NSString* localAbbreviation = [localTimeZone abbreviation];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:localAbbreviation]];
    NSDate *date = [formatter dateFromString:created];
    [formatter setDateFormat:[NSString stringWithFormat:@"eeee MM/dd/yy"]];
	return [formatter stringFromDate:date];
}

+ (NSString *)stringDateFormatFromDate:(NSString *)created WithType:(enumDateFormatType)type
{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
    NSString* localAbbreviation = [localTimeZone abbreviation];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:localAbbreviation]];
    NSDate *date = [formatter dateFromString:created];
    switch (type) {
        case enumDateFormatType_dd_MM_yyyy:
        {
            [formatter setDateFormat:[NSString stringWithFormat:@"dd.MM.yyyy"]];
            return [formatter stringFromDate:date];
        }
            break;
        case enumDateFormatType_M_d_yyyy:
        {
            [formatter setDateFormat:[NSString stringWithFormat:@"M.d.yyyy"]];
            return [formatter stringFromDate:date];
        }
            break;
        case enumDateFormatType_EEE_bold:{
            [formatter setDateFormat:[NSString stringWithFormat:@"EEEE"]];
            return [formatter stringFromDate:date];
        }
    
            break ;
        case enumDateFormatType_M_d_yy_HH_mm_aa:
        {
            [formatter setDateFormat:[NSString stringWithFormat:@"M/d/yy, hh:mm a"]];
            return [formatter stringFromDate:date];
        }
            break;
        case enumDateFormatType_MMM_ddd:
        {
            [formatter setDateFormat:[NSString stringWithFormat:@"MMMM d"]];
            return [formatter stringFromDate:date];
        }break;
            
        case enumDateFormatType_yyyyMMdd:
        {
            [formatter setDateFormat:[NSString stringWithFormat:@"yyyyMMdd"]];
            return [formatter stringFromDate:date];
            break;
        }
            
        default:
            break;
    }
}


#pragma mark - UIColor

+ (UIColor *)colorFromHexString:(NSString *)hexString {
    NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    if([cleanString length] == 3) {
        cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", 
                       [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                       [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                       [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
    }
    if([cleanString length] == 6) {
        cleanString = [cleanString stringByAppendingString:@"ff"];
    }
    
    unsigned int baseValue;
    [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];
    
    float red = ((baseValue >> 24) & 0xFF)/255.0f;
    float green = ((baseValue >> 16) & 0xFF)/255.0f;
    float blue = ((baseValue >> 8) & 0xFF)/255.0f;
    float alpha = ((baseValue >> 0) & 0xFF)/255.0f;
    
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}


@end

#pragma mark - UIImage

@implementation UIImage (Extras)

- (UIImage *)imageByScalingToSize:(CGSize)size withOption:(enumImageScalingType)type {
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize targetSize;
    CGRect drawRect;
    
    if (type == enumImageScalingType_Top) {
        targetSize = CGSizeMake(sourceImage.size.width, size.height*sourceImage.size.width/size.width);
        drawRect = CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height);
    }
    else if (type == enumImageScalingType_TargetSize) {
        targetSize = CGSizeMake(sourceImage.size.width, size.height*sourceImage.size.width/size.width);
        drawRect = CGRectMake(0, 0, targetSize.width, targetSize.height);
    }
    else if (type == enumImageScalingType_Center_ScaleSize) {
        CGFloat scaleFactor;
        CGFloat widthFactor = sourceImage.size.width/size.width;
        CGFloat heightFactor = sourceImage.size.height/size.height;
        
        if (widthFactor < heightFactor)
            scaleFactor = heightFactor;
        else
            scaleFactor = widthFactor;
        
        CGFloat scaledWidth  = size.width*scaleFactor;
        CGFloat scaledHeight = size.height*scaleFactor;
        targetSize = CGSizeMake(scaledWidth, scaledHeight);
        
        drawRect = CGRectMake((scaledWidth - sourceImage.size.width)/2, (scaledHeight - sourceImage.size.height)/2, sourceImage.size.width, sourceImage.size.height);
    }
    else if (type == enumImageScalingType_Center_FullSize) {
//        CGFloat scaleFactor;
//        CGFloat widthFactor = sourceImage.size.width/size.width;
//        CGFloat heightFactor = sourceImage.size.height/size.height;
//        
//        if (widthFactor < heightFactor)
//            scaleFactor = widthFactor;
//        else
//            scaleFactor = heightFactor;
//        
//        CGFloat scaledWidth  = size.width*scaleFactor;
//        CGFloat scaledHeight = size.height*scaleFactor;
//        targetSize = CGSizeMake(scaledWidth, scaledHeight);
//        
//        drawRect = CGRectMake(-(sourceImage.size.width - scaledWidth)/2, -(sourceImage.size.height - scaledHeight)/2, sourceImage.size.width, sourceImage.size.height);
        
        //TaiT: 06/24/13 update scale full size, just scale one side (width or height)
        CGFloat scaleFactor;
        CGFloat widthFactor = sourceImage.size.width/size.width;
        CGFloat heightFactor = sourceImage.size.height/size.height;
        
        if (widthFactor < heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        
        CGFloat scaledWidth  = sourceImage.size.width/scaleFactor;
        CGFloat scaledHeight = sourceImage.size.height/scaleFactor;
        
        targetSize = size;
        drawRect = CGRectMake(-(scaledWidth - size.width)/2, -(scaledHeight - size.height)/2, scaledWidth, scaledHeight);
    }
    else {
        targetSize = CGSizeMake(size.width*sourceImage.size.height/size.height, sourceImage.size.height);
        drawRect = CGRectMake(0, 0, sourceImage.size.width, sourceImage.size.height);
    }
    
    //Qasim 10/11/12
    //VKLog(@"targetSize.width:%f, targetSize.height:%f, drawRect.origin.x:%f, drawRect.origin.y:%f, drawRect.size.width:%f, drawRect.size.height:%f", targetSize.width, targetSize.height, drawRect.origin.x, drawRect.origin.y, drawRect.size.width, drawRect.size.height);
    UIGraphicsBeginImageContext(targetSize);
    
    // draw image
    [sourceImage drawInRect:drawRect];
    
    // grab image
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    if(newImage == nil) VKLog(@"could not scale image");
    return newImage;
}

- (NSData*)getImageDataWithMaxSize:(CGSize)size andQuality:(float)quality {
    CGSize origSize = self.size;
    NSInteger newHeight = origSize.height;
    NSInteger newWidth = origSize.width;
    
    NSInteger maxHeight;
    NSInteger maxWidth;
    if (size.width <= 0 || size.height <= 0) {
        maxHeight = HEIGHT_IMAGE_REDUCED_QUALITY_DEFAULT;
        maxWidth = WIDTH_IMAGE_REDUCED_QUALITY_DEFAULT;
    }
    else {
        maxHeight = size.height;
        maxWidth = size.width;
    }
    
    //Image is taller than it is wide or square
    if(origSize.height > origSize.width && origSize.height > maxHeight) {
        float scale = origSize.height/maxHeight;
        newHeight = maxHeight;
        newWidth = origSize.width/scale;
        
    }
    //Image is wider than it is tall
    else if(origSize.width > origSize.height && origSize.width > maxWidth) {
        float scale = origSize.width/maxWidth;
        newWidth = maxWidth;
        newHeight = origSize.height/scale;
        
    }
    //Else image is too small to need resizing
    
    CGSize newSize = CGSizeMake(newWidth, newHeight);
    NSUInteger imgSize = 0;
    
    float imgQuality = 0.0;
    if (quality <= 0) {
        imgQuality = QUALITY_IMAGE_REDUCED_QUALITY_DEFAULT;
    }
    else {
        imgQuality = quality;
    }
    
    NSData* resizedImageData = nil;
    do {
        UIGraphicsBeginImageContext(newSize);
        [self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        resizedImageData = UIImageJPEGRepresentation(newImage, imgQuality);
        imgSize = [resizedImageData length];
        imgQuality -= .1;
        
        //VKLog(@"resizedImageData size = %d", imgSize);
    } while (imgSize > 512000 && imgQuality > 0);
    
    return resizedImageData;
}

@end

#pragma mark - NSString

@implementation NSString (Extras)

- (BOOL)isAvailableWithCheckingType:(enumNSStringExtrasCheckingType)checkingType {
    if (checkingType == enumNSStringExtrasCheckingType_KardBuilder_KardName) {
        if (self.length < 2) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_NAME_TOO_SHORT(@"Kard"));
            return NO;
        }
        else if (self.length > 20) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_NAME_TOO_LONG(@"Kard"));
            return NO;
        }
        
        NSString *regexKardName = @"[a-zA-Z0-9- ']{2,20}"; 
        NSPredicate *preKardName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexKardName]; 
        if (![preKardName evaluateWithObject:self]) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_NAME_MUST_BE_AVAILABLE(@"Kard"));
            return NO;
        }
    }
    else if (checkingType == enumNSStringExtrasCheckingType_KardBuilder_ProfileName) {
        if (self.length < 2) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_NAME_TOO_SHORT(@"Profile"));
            return NO;
        }
        else if (self.length > 20) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_NAME_TOO_LONG(@"Profile"));
            return NO;
        }
        
        NSString *regexKardName = @"[a-zA-Z0-9- ]{2,20}"; 
        NSPredicate *preKardName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexKardName]; 
        if (![preKardName evaluateWithObject:self]) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_NAME_MUST_BE_AVAILABLE(@"Profile"));
            return NO;
        }
    }
    else if (checkingType == enumNSStringExtrasCheckingType_KardBuilder_Profile_FirstName) {
        if (self.length < 1) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_PROFILE_FIRST_NAME_TOO_SHORT);
            return NO;
        }
        else if (self.length > 32) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_PROFILE_FIRST_NAME_TOO_LONG);
            return NO;
        }
        
        NSString *regexKardName = @"[a-zA-Z0-9- ]{1,32}"; 
        NSPredicate *preKardName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexKardName]; 
        if (![preKardName evaluateWithObject:self]) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_PROFILE_FIRST_NAME_MUST_BE_AVAILABLE);
            return NO;
        }
    }
    else if (checkingType == enumNSStringExtrasCheckingType_KardBuilder_Profile_LastName) {
        if (self.length < 1) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_PROFILE_LAST_NAME_TOO_SHORT);
            return NO;
        }
        else if (self.length > 32) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_PROFILE_LAST_NAME_TOO_LONG);
            return NO;
        }
        
        NSString *regexKardName = @"[a-zA-Z0-9- ]{1,32}"; 
        NSPredicate *preKardName = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexKardName]; 
        if (![preKardName evaluateWithObject:self]) {
            ALERT(@"", STRING_ALERT_MESSAGE_KARD_BUILDER_PROFILE_LAST_NAME_MUST_BE_AVAILABLE);
            return NO;
        }
    }
    else if (checkingType == enumNSStringExtrasCheckingType_Email)
    {
        //http://stackoverflow.com/questions/5428304/email-validation-on-textfield-in-iphone-sdk
        NSString* str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        if (![emailTest evaluateWithObject:str]) {
            //ALERT(@"", STRING_ALERT_MESSAGE_EMAIL_VALIDATION_ERROR);
            return NO;
        }
    }
    else if (checkingType == enumNSStringExtrasCheckingType_US_Phone)
    {
        //http://megasnippets.com/source-codes/csharp/validate_us_phone_number_regex
        NSString* str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *phoneRegex = @"^[(]?[2-9][0-9]{2}[)]?[ -]?[0-9]{3}[ -]?[0-9]{4}$";
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
        if (![phoneTest evaluateWithObject:str]) {
            ALERT(@"", STRING_ALERT_MESSAGE_PHONE_VALIDATION_ERROR);
            return NO;
        }
    }
    else if (checkingType == enumNSStringExtrasCheckingType_World_Phone)
    {
        //http://megasnippets.com/source-codes/csharp/validate_us_phone_number_regex
        NSString* str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *phoneRegex = @"^[0-9()+-]+$";
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
        if (![phoneTest evaluateWithObject:str]) {
            ALERT(@"", STRING_ALERT_MESSAGE_PHONE_VALIDATION_ERROR_WORLD);
            return NO;
        }
    }
    else if (checkingType == enumNSStringExtrasCheckingType_Website)
    {
        //http://stackoverflow.com/questions/8571062/url-validation-function-improving
        NSString* str = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *urlRegEx = @"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
        
        NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
        if (![urlTest evaluateWithObject:str]) {
            ALERT(@"", STRING_ALERT_MESSAGE_WEBSITE_VALIDATION_ERROR);
            return NO;
        }
    }
    return YES;
}

@end
